package com.example.servlet.manager;

import com.example.email.EmailSender;
import com.example.entity.Manager;
import com.example.entity.Order;
import com.example.entity.Ticket;
import com.example.entity.User;
import com.example.service.OperationService;
import com.example.service.impl.OperationServiceImpl;
import com.example.utils.MybatisUtil;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;

import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;

@WebServlet("/manager_flight_operation")
public class mFlightOperationServlet extends HttpServlet {
    private OperationService service;
    private SqlSession sqlSession;
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        sqlSession = MybatisUtil.getSession();
        service = new OperationServiceImpl(sqlSession);
    }
    @Override
    public void destroy() {
        sqlSession.close();
        super.destroy();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String fid = req.getParameter("f_id");
        String numberPart = fid.replaceAll("\\D+", ""); // 移除所有非数字字符
        int f_id = Integer.parseInt(numberPart);
        String action = req.getParameter("action");
        try {
            switch (action) {
                case "depart":
                    service.ticketFlightStart(f_id);
                    service.orderFlightStart(f_id);
                    service.commit();
                    req.getSession().setAttribute("flight_operation_success", new Object());
                    break;
                case "arrival":
                    if(service.flightArrive(f_id)==0){
                        service.ticketFlightStart(f_id);
                    }
                    service.commit();
                    req.getSession().setAttribute("flight_operation_success", new Object());
                    break;
                default:
                    break;
            }
            resp.sendRedirect("manager_flight");
        } catch (Exception e) {
            e.printStackTrace();
            service.rollback();
            req.getSession().setAttribute("flight_operation_failure", new Object());
            resp.sendRedirect("manager_flight");
        }
    }
}
